package com.mep.rbac.enhancer;

import com.mep.common.utils.FastJsonUtils;
import com.mep.rbac.dao.SysUserRoleMapper;
import com.mep.rbac.model.SysMenu;
import com.mep.rbac.model.SysRole;
import com.mep.rbac.model.SysUser;
import com.mep.rbac.model.SysUserRole;
import com.mep.rbac.service.SysRoleService;
import com.mep.rbac.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JwtTokenEnhancer implements TokenEnhancer {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
//        String username = (String) oAuth2Authentication.getUserAuthentication().getPrincipal();
//        Map<String, Object> info = new HashMap<>();
//        SysUser sysUser = sysUserService.findByName(username);
//        List<SysUserRole> sysUserRoleList = sysUserRoleMapper.findUserRoles(sysUser.getId());
//
//
//        List<SysRole> sysRoleList = new ArrayList<>();
//        for (SysUserRole sysUserRole : sysUserRoleList) {
//            SysRole sysRole = sysRoleService.findById(sysUserRole.getRoleId());
//            List<SysMenu> sysMenuList = sysRoleService.findRoleMenus(sysUserRole.getRoleId());
//            sysRole.setSysMenuList(sysMenuList);
//            sysRoleList.add(sysRole);
//        }
//        sysUser.setSysRoleList(sysRoleList);
//        String sysUserJson = FastJsonUtils.toJSONNoFeatures(sysUser);
//        //info.put("details", sysUser);
//
//        ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(info);
        return oAuth2AccessToken;
    }

}